const http = require('http')
const fs = require('fs')
const S = require('string')

// const url = "http://www.51ape.com/skin/ape/php/qx_2.php?qx=%e9%98%bf%e7%89%9b"

module.exports.getUrlAndNameSingle = function (url, singerName, singerId) {
    http.get(url, res => {
        if (res.statusCode !== 200) {
            console.log('404')
            return
        }
        var html = ''
        res.on('data', data => {
            html += data
        })

        res.on('end', () => {
            // console.log(html.length, typeof html)
            let musicUrl = html.match(/http:\/\/www.51ape.com\/.{0,25}\.html/g),
                musicName = html.split('</li>')
                .map(v => S(v).between(`t20d">`, `</a>`).s)
                .filter(v => v.length !== 0);
            if (musicName.length === musicUrl.length) { // 数量是否一样，如果都错了，emmmmm
                let path = '\\..\\Data\\singerMusicInfo\\' + singerId + '.json',
                    res = [];
                for (let i = 0; i < musicName.length; i++) {
                    let name = musicName[i].match(/(?<=-\s).*(?=\.)/)
                    res.push({
                        musicUrl: musicUrl[i],
                        musicName: name[name.length - 1]
                    })
                    // console.log(res)
                }
                fs.writeFile(__dirname + path, JSON.stringify(res), err => {
                    if (err) {
                        console.error('歌手歌曲信息文件写入失败！')
                    } else {
                        // console.log('歌手歌曲信息文件写入成功！')
                    }
                })
            } else {
                // console.log('歌曲地址/歌名 解析有误')
                console.log(singerId)
            }
            // console.log(musicName[musicName.length - 1] + '?', musicName.length)
            console.log(musicUrl, musicUrl.length)
            console.log(musicName, musicName.length)

        })
    }).on('error', err => {
        // console.log('errorMessage: ' + err)
        console.log(singerId)
    })
}